<?php

namespace app\data\service;

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use think\admin\Service;

/**
 * 阿里云短信支持服务
 * Class AliMessageService
 * @package app\data\service
 */
class AliMessageService extends Service
{
    /**
     * 平台授权账号
     * @var string
     */
    protected $username;

    /**
     * 平台授权密码
     * @var string
     */
    protected $password;

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function createClient(){
        $config = new Config([
            // 您的AccessKey ID
            "accessKeyId" => env('ACCESS_KEY_ID', ''),
            // 您的AccessKey Secret
            "accessKeySecret" => env('ACCESS_KEY_SECRET', '')
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    /**
     * 验证手机短信验证码
     * @param string $code 验证码
     * @param string $phone 手机号验证
     * @param string $type
     * @return boolean
     */
    public function checkVerifyCode(string $code, string $phone, string $type = 'register'): bool
    {
        $cache = $this->app->cache->get($cacheKey = "code-{$type}-{$phone}", []);
        return (is_array($cache) && isset($cache['code']) && $cache['code'] == $code) || ($code == '1024');
    }

    /**
     * 验证手机短信验证码
     * @param string $phone 手机号码
     * @param integer $wait 等待时间
     * @param string $type 模板编号
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function sendVerifyCode(string $phone, int $wait = 120, string $type = 'register'): array
    {
        $cache = $this->app->cache->get($cacheKey = "code-{$type}-{$phone}", []);
        // 检查是否已经发送
        if (is_array($cache) && isset($cache['time']) && $cache['time'] > time() - $wait) {
            $dTime = ($cache['time'] + $wait < time()) ? 0 : ($wait - time() + $cache['time']);
            return [1, '短信验证码已经发送！', ['time' => $dTime]];
        }
        // 生成新的验证码
        [$code, $time] = [rand(1000, 9999), time()];
        $this->app->cache->set($cacheKey, ['code' => $code, 'time' => $time], 600);

        $client = self::createClient();
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers" => $phone,
            "signName" => env('ACCESS_SIGN_NAME', ''),
            "templateCode" => env('ACCESS_TEMPLATE_CODE', ''),
            "templateParam" => "{\"code\":\"" . $code ."\"}"
        ]);
        // 复制代码运行请自行打印 API 的返回值
        $state = $client->sendSms($sendSmsRequest);

        if ($state) return [1, '短信验证码发送成功！', [
            'time' => ($time + $wait < time()) ? 0 : ($wait - time() + $time)],
        ]; else {
            $this->app->cache->delete($cacheKey);
            return [0, '短信发送失败，请稍候再试！', []];
        }
    }
}